package org.ef.anticheck;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 远程 Query，从服务器查询
 * 
 * @author zenglu.liu
 */
public class RemoteQuery implements Query {

	private final String urlPattern;

	private final HttpClient httpClient;

	// TODO change timeout
	private static final int TIMEOUT_CONNECTION = 10000;

	private static final int TIMEOUT_SOCKET = 10000;

	public RemoteQuery(final String urlPattern) {
		this.urlPattern = urlPattern;

		final HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);
		HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);

		this.httpClient = new DefaultHttpClient(httpParameters);
	}

	public Recoder execute(final String phone) throws QueryException {
		final String url = this.urlPattern.replace("{phone}", phone);

		HttpResponse response = null;
		try {
			response = this.httpClient.execute(new HttpGet(url));
		} catch (final Throwable t) {
			throw new QueryException(t);
		}

		final StatusLine statusLine = response.getStatusLine();
		if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
			try {
				response.getEntity().getContent().close();
			} catch (final Throwable t) {
				throw new QueryException(t);
			}
		}

		final ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			response.getEntity().writeTo(out);
			out.close();
		} catch (final IOException e) {
			throw new QueryException(e);
		}

		JSONObject o = null;
		try {
			o = new JSONObject(out.toString());
		} catch (final JSONException e) {
			throw new QueryException(e);
		}

		final Recoder r = new Recoder();

		try {
			r.id = o.getInt("i");
			r.phone = phone;
			r.info = o.getString("r") + o.getString("sp") + o.getString("m");
		} catch (final JSONException e) {
			throw new QueryException(e);
		}

		return r;
	}

	public void dispose() {
		// do nothing.
	}
}